/**
 * Created by CHENRI4 on 10/18/2016.
 */
Ext.define('sso.admin.user.controller.UserController',{
    extend:'Ext.app.Controller',
    models:[
        'sso.admin.user.model.UserModel'
    ],
    stores:[
        'sso.admin.user.store.UserStore'
    ],
    ref:[
        {selector:'#userGird'},
        {selector:'#userSearchBar'},
        {selector:'#btnUserSync'}
    ],
    init:function (application) {
        this.control({
            '#userSearchBar':{
                searchClick:this.onSearchClick,
            },
            '#btnUserReset':{
                click:this.onClickReset
            },
            '#btnUserSync':{
                click:this.syncUserView
            },
            '#btnSyncUser':{
                click:this.syncUser
            },
            '#userGird':{
                'select': this.onSelect,
                'deselect': this.onDeselect,
                'afterrender':this.onUserGridRender
            },
            '#btnDelUser':{
                click:this.onDelUser
            },
            '#UserPagingToolBar':{
                beforechange:this.beforePageChange
            }
        });
        this.callParent(arguments);
    },
    onUserGridRender:function (grid) {
        grid.getStore().load();
    },
    onSearchClick:function (formValues) {
        console.log(formValues);
        var userId=formValues.userId;
        var name=formValues.name;
        var phone=Number(formValues.phone);
        var gtTime=changeTimeToRow(formValues.gtDate,0);
        var ltTime=changeTimeToRow(formValues.ltDate,1);
        var filters=[];
        addFilter('uId','EQ',userId,filters);
        addFilter('name','EQ',name,filters);
        addFilter('phone','EQ',phone,filters);
        addFilter('createTime','GTE',gtTime,filters);
        addFilter('createTime','LTE',ltTime,filters);
        var store=Ext.getCmp('userGird').getStore();
        store.proxy.extraParams='';
        if(filters.length>0){

            store.proxy.extraParams = {
                searchFilters: Ext.JSON.encode(filters),
                page:1,
            };
        }else{
            store.loadPage(1);
        }
    },
    onClickReset:function () {
        this.resetCombo();
    },
    resetCombo:function(){
        Ext.getCmp('btnUserReset').up('form').getForm().reset();
        var userIDCombo = Ext.getCmp('userSearchUserIdCombo');
        var displayNameCombo = Ext.getCmp('userSearchDisplayNameCombo');
        userIDCombo.select(userIDCombo.getStore().first());
        displayNameCombo.select(displayNameCombo.getStore().first());

    },
    syncUserView:function (button) {
        var userWindow = Ext.create('sso.admin.user.view.SyncUserWindowView',{
            width:400,
            height:150
        })
        userWindow.show();
    },
    syncUser:function (button) {
        var me = this;
        var syncUserWindow = button.up('window');
        var store = Ext.getCmp('userGird').getStore();
        var userId = syncUserWindow.down('textfield').getValue();
        syncUserWindow.destroy();
        // Ext.Ajax.request({
        //     url: 'api/user/syncuser',
        //     method: 'POST',
        //     async: false,
        //     params:{
        //         userid:userId
        //     },
        //     success: function(resp,opts) {
        //         result = Ext.JSON.decode(resp.responseText);
        //         syncUserWindow.destroy();
        //         store.reload();
        //     },
        //     failure: function(resp,opts) {
        //         syncUserWindow.destroy();
        //         Ext.Msg.alert(Constants.MESSAGE.WARNING,"Sync user failed.");
        //     }
        // });
    },
    onSelect:function (rowmodel , record , index , eOpts) {
        Ext.getCmp('btnDelUser').enable();

    },
    onDeselect:function () {
        Ext.getCmp('btnDelUser').disable();
    },
    onDelUser:function (btn) {
        var items = btn.findParentByType('UserGrid').getSelectionModel().getSelection();
        if(items.length === 0) {
            Ext.Msg.alert('warning', 'choose items is null');
            return;
        }
        var store = btn.findParentByType('UserGrid').getStore();
        Ext.Msg.confirm('Confirm Delete', 'Are you sure to delete the item(s)?', callback);
        function callback(id) {
            if(id === "yes"){
                store.remove(items);
                Ext.getCmp('btnDelUser').disable();
            };
        };
    },
    beforePageChange:function () {
        Ext.getCmp('btnDelUser').disable();
    }
})

function changeTimeToRow(time,mark){
    var rawTime='';
    if(time!=''){
        // var times=time.split('-');
        // console.log(moment(time).format('x'));
        // var ucdTime='';
        // if(mark==0){
        //     ucdTime=Ext.Date.utc(times[0],times[1],times[2]);
        // }else{
        //     ucdTime=Ext.Date.utc(times[0],times[1],times[2],24,60,60,1000);
        // }
        // console.log(ucdTime);
        // console.log(moment().toISOString());
        // var time2=moment().format('x');
        // console.log(time2);
        // moment.locale('en');
        // rawTime=moment(ucdTime).format('x');
        // // console.log(ucdTime);
        if(mark==0){
            rawTime=(moment.tz(time, "Europe/London")).format('x');
        }else{
            rawTime=(moment.tz(time+' 23:59:59.999', "Europe/London")).format('x');
        }
    }
    return rawTime;
}

function addFilter(filedName,operator,value,filters) {
    var filter=null;
    if(value!=''){
        filter={};
        filter.fieldName=filedName;
        filter.operator=operator;
        filter.value=value;
    }
    if(filter!=null){
        filters.push(filter);
    }
    return filters;
}